//
//  WFNetworking.m
//  afn
//
//  Created by MacBook on 16/12/13.
//  Copyright © 2016年 MacBook. All rights reserved.
//

#import "WFNetworking.h"

@implementation WFNetworking
+ (instancetype)deafultManeger{//初始化
    static WFNetworking * manager;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        manager = [[WFNetworking alloc] init];
    });
    return manager;
}

static AFHTTPSessionManager *manager;

+(AFHTTPSessionManager *)sharedHttpSessionManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
    });
    
    return manager;
}
- (void)requestURL:(NSString *)URLString HttpMethod:(HttpMethod)method Parameters:(id)parameters ResponseSerializerType:(ResponseType)type Timeout:(CGFloat)time Succeed:(void (^)(id result))succeed Failure:(void (^)(NSError * err))failure{
    
    //创建AF单利
    AFHTTPSessionManager * manager = [WFNetworking sharedHttpSessionManager];//这样才不会造成内存泄漏
    
    //判断返回数据解析格式
    if (!type) {
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    }
    else{
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    
    //设置超时时间
    manager.requestSerializer.timeoutInterval = time;
    
    // 5.选择请求方式 GET 或 POST
    switch (method) {
        case GET:
        {
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                
                if (!type) {
                    succeed(responseObject);
                }
                else{
                    NSString *jsonString =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    succeed(jsonString);
                }
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
                failure(error);
                
            }];
        }
            break;
            
        case POST:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                
                if (!type) {
                    succeed(responseObject);
                }
                else{
                    NSString *jsonString =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                    succeed(jsonString);
                }
                
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
                failure(error);
                
            }];
        }
            break;
            
        default:
            break;
    }
}

@end
